package org.luo.gateway.filter;


import org.luo.common.utils.JwtUtil;
import org.luo.gateway.config.AuthProperties;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;

@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    @Autowired
    private AuthProperties authProperties;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();

        if(isExclude(path)){
            return chain.filter(exchange);
        }

        HttpHeaders headers = request.getHeaders();
        List<String> authorization = headers.get("Authorization");
        String token = "";
        if(authorization != null){
            token = authorization.get(0);
        }


        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            Integer id = (Integer) claims.get("id");
            String username = (String) claims.get("username");

            ServerWebExchange sw = exchange.mutate().request(builder -> builder.header("id", id.toString())
                    .header("username", username)
            ).build();

            return chain.filter(sw);

        }catch (Exception e){
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }



    }

    @Override
    public int getOrder() {
        return 0;
    }

    private boolean isExclude(String path){

        for(String pattern : authProperties.getExcludePaths()){
            if(antPathMatcher.match(pattern, path)){
                return true;
            }
        }
        return false;
    }
}
